package com.blq.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.blq.common.annotation.Anonymous;
import com.blq.common.core.domain.R;
import com.blq.pay.service.IWxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
@Validated
@Api(value = "微信支付接口", tags = {"微信支付接口"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/wxPay")
public class WxPayController {

    private final IWxPayService wxPayService;

    /**
     * 微信小程序支付回调
     * @param request
     * @return
     */
    @Anonymous
    @PostMapping("/notifyJsApi")
    @ApiOperation("微信回调")
    public String notifyJsApi(HttpServletRequest request) {
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                log.info(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = wxPayService.payBack(resXml,3);
            log.info("成功");
            log.info(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("微信手机支付失败:" + e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            log.info("失败");
            log.info(result);
            return result;
        }
    }

    /**
     * 开发环境点击立即支付调用此接口
     * @return
     */
    @PostMapping("/notifyJsApiTest")
    @ApiOperation("微信回调")
    public R<Object> notifyJsApi(@RequestBody JSONObject jsonObject) {
        return R.ok(wxPayService.payBackTest(jsonObject.getString("orderId")));
    }

}
